package com.sgg.gulimall_product.generator.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgg.gulimall_product.generator.domain.PmsCategory;
import com.sgg.gulimall_product.generator.service.PmsCategoryService;
import com.sgg.gulimall_product.generator.mapper.PmsCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 商品三级分类业务类 @Date 2021/9/28 0028 10:08 @Author FileWorld
 */
@Service
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryMapper, PmsCategory>
        implements PmsCategoryService {

    @Autowired
    private PmsCategoryMapper categoryMapper;

    /**
     * 获取三级分类
     *
     * @return
     */
    @Override
    public List<PmsCategory> getCategoryList() {
        //        所有商品信息
        List<PmsCategory> pmsCategories = categoryMapper.selectList(null);

        return pmsCategories.stream()
                .filter(items -> items.getParentCid() == 0)
                .map(
                        item -> {
                            item.setChildren(categoryTree(item, pmsCategories));
                            return item;
                        })
                .collect(Collectors.toList());
    }

    private List<PmsCategory> categoryTree(PmsCategory item, List<PmsCategory> pmsCategories) {
        return pmsCategories.stream()
                .filter(pmsCategory -> pmsCategory.getParentCid().equals(item.getCatId()))
                .map(
                        PmsCategory -> {
                            PmsCategory.setChildren(categoryTree(PmsCategory, pmsCategories));
                            return PmsCategory;
                        })
                .collect(Collectors.toList());
    }
}
